//
//  HomeTableViewController.swift
//  WeiBo09
//
//  Created by 裘明 on 15/8/31.
//  Copyright © 2015年 qm. All rights reserved.
//

import UIKit
import SVProgressHUD

class HomeTableViewController: BaseTableViewController {
    
    /// 微博列表数据模型
    lazy var statusListViewModel = StatusListViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 如果用户没有登录就跳转到访客模式
        if !UserAccountViewModel.sharedUserAccount.userLogin {
            
            vistorLogin?.setupinfo(nil, message:"关注一些人，回这里看看有什么惊喜")
            return
        }

        prepareTableView()
        
        loadData()
        
    }
    
    private func prepareTableView() {
        
        // 注册可重用cell
        tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: MQStatusForwordCellID)
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: MQStatusNormalCellID)
        // 提示：如果不使用自动计算行高，UITableViewAutomaticDimension，一定不要设置底部约束
        tableView.estimatedRowHeight = 300

        // 取消分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        // 下拉刷新
        refreshControl = RefreshController()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        // 上拉刷新
        pullupView.startAnimating()
        tableView.tableFooterView = pullupView
        
    }
    
    /// 加载数据
    func loadData() {
        
        refreshControl?.beginRefreshing()
        
        statusListViewModel.loadStatus(isPullupRefresh: pullupView.isAnimating()).subscribeNext({ (result) -> Void in
            

            
            let count =  (result as! NSNumber).integerValue
            self.showPulldownTips(count)
    
            }, error: { (error) -> Void in
                
                self.endLoadData()
                
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                
            }) {
                
                self.endLoadData()
                // 刷新表格
                self.tableView.reloadData()
        }
        
    }
    
    private func showPulldownTips(count: Int) {
        let title = count == 0 ? "没有新微博" : "刷新到\(count)条微博"
        let height: CGFloat = 44
        let rect = CGRect(x: 0, y: -2 * height, width: UIScreen.mainScreen().bounds.width, height: height)
        pulldownTipLabel.text = title
        pulldownTipLabel.frame = rect
        
        UIView.animateWithDuration(1.2, animations: {
            
            self.pulldownTipLabel.frame = CGRectOffset(rect, 0, 3 * height)
            }) { (_) -> Void in
                
                UIView.animateWithDuration(1.2) {
                    self.pulldownTipLabel.frame = rect
                }
        }
        
    }
    
    ///  线束刷新数据
    private func endLoadData() {
        // 关闭刷新控件
        self.refreshControl?.endRefreshing()
        // 关闭上拉刷新动画
        self.pullupView.stopAnimating()
    }
    
    
    //  MARK: - 懒加载控件
    /// - 下拉提示标签
    private lazy var pulldownTipLabel: UILabel = {
       let label = UILabel(title: nil, color: UIColor.whiteColor(), fontSize: 18)
        label.backgroundColor = UIColor.orangeColor()
        label.textAlignment = NSTextAlignment.Center
        
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        
        return label
        
    }()
    
    /// 上拉刷新
    private lazy var pullupView: UIActivityIndicatorView = {
       
        let activity = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        activity.color = UIColor.darkGrayColor()
        
        return activity
        
    }()


}

extension HomeTableViewController {
    
    // 1.数据行数
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListViewModel.statuses.count
    }
    
    // 2.返回cell
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        // 1.从模型中获取数据
        let statusViewModel = statusListViewModel.statuses[indexPath.row] 

        // 2.寻找可重用cell
        let cell = tableView.dequeueReusableCellWithIdentifier(statusViewModel.cellID, forIndexPath: indexPath) as! StatusCell
        
        // 3.给cell赋值
        cell.statusViewModel = statusViewModel
        
        // 4.判断当前的indexPath是否是数组的最后一项，如果是，开始上拉刷新
        if (indexPath.row == statusListViewModel.statuses.count - 1) && !pullupView.isAnimating() {
           
            pullupView.startAnimating()
            
            loadData()
            
        }
        // 4.返回cell
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
//        print(indexPath)
        // 1.获得模型
        let viewModel = statusListViewModel.statuses[indexPath.row] 
        
        if viewModel.rowHeight > 0 {
            return viewModel.rowHeight
        }
        
        // 2.获得cell
        let cell = tableView.dequeueReusableCellWithIdentifier(MQStatusNormalCellID) as! StatusCell
        
        // 3.记录行高
        viewModel.rowHeight = cell.rowHeight(viewModel)
        // 3.返回行高
        return viewModel.rowHeight
    }
    
}


